import SearchTablePage from '@/components/SearchTablePage';
import { PERMISSION_KEY_TERMINAL_MODLE } from '@/constants';
import { getBrandSelect } from '@/services/terminal/brand';
import {
  addTerminalModel,
  deleteTerminalModelById,
  getTerminalModelById,
  getTerminalModelListByPage,
  updateTerminalModel,
} from '@/services/terminal/model';
import { getTerminalTypeSelect } from '@/services/terminal/type';
import { formatOptions, optionsToValueEnum } from '@/utils/dataTransferUtils';
import { useRequest } from '@umijs/max';
import { message } from 'antd';

const Brand: React.FC = () => {
  const {
    data: brandSelect,
    error: getBrandSelectError,
    refresh: refreshBrandSelect,
  } = useRequest(getBrandSelect);

  if (getBrandSelectError) {
    message.error(getBrandSelectError.message);
    console.error('error', getBrandSelectError);
  }

  const {
    data: terminalTypeSelect,
    error: getTerminalTypeError,
    refresh: refreshTerminalTypeSelect,
  } = useRequest(getTerminalTypeSelect);

  if (getTerminalTypeError) {
    message.error(getTerminalTypeError.message);
    console.error('error', getTerminalTypeError);
  }

  return (
    <>
      <SearchTablePage<API.TerminalModel>
        tableName="设备型号"
        getRowById={getTerminalModelById}
        updateRow={updateTerminalModel}
        addRow={addTerminalModel}
        deleteRowById={deleteTerminalModelById}
        getRowsByPage={getTerminalModelListByPage}
        permissionKey={PERMISSION_KEY_TERMINAL_MODLE}
        rowSelection={false}
        onModalFormOpen={() => {
          refreshBrandSelect();
          refreshTerminalTypeSelect();
        }}
        columns={[
          {
            title: '设备型号 ID',
            dataIndex: 'id',
            hideInTable: true,
            hideInSearch: true,
            hideInModal: true,
          },
          {
            title: '设备型号名称',
            dataIndex: 'name',
            showDetail: true,
            rules: [{ required: true }],
          },
          {
            title: '设备厂商',
            dataIndex: 'brandId',
            hideInSearch: true,
            valueType: 'select',
            valueEnum: optionsToValueEnum(brandSelect, { label: 'name', value: 'id' }),
            options: formatOptions(brandSelect, { label: 'name', value: 'id' }),
            rules: [{ required: true }],
          },
          {
            title: '设备类型',
            dataIndex: 'typeId',
            hideInSearch: true,
            valueType: 'select',
            valueEnum: optionsToValueEnum(terminalTypeSelect, { label: 'cnName', value: 'id' }),
            options: formatOptions(terminalTypeSelect, { label: 'cnName', value: 'id' }),
            rules: [{ required: true }],
          },
          {
            title: '创建时间',
            dataIndex: 'createTime',
            valueType: 'dateTime',
            hideInSearch: true,
            hideInModal: true,
          },
        ]}
      />
    </>
  );
};

export default Brand;
